var express = require('express');
var router = express.Router();
var { conn, isError, dateFormat } = require("../untils");
var { aesEncrypt, keys } = require("../untils/ase");
var { waterfall } = require("async");

router.post('/register', function (req, res) {
  var session_username = req.session.username;
  var body = req.body;
  var username = body.username;
  var usertel = body.usertel;
  conn((err, db) => {
    isError(err, res, db);
    var news_user_info = db.collection("news_user_info");
    waterfall([
      (callback) => {
        news_user_info.findOne({ status: 1, $or: [{ username: username }, { usertel: usertel }] }, {}, (err, result) => {
          if (err) {
            callback(err, null);
          } else {
            if (result) {
              callback(null, true);
            } else {
              callback(null, false);
            }
          }
        });
      },
      (args, callback) => {
        if (!args) {
          body.status = 1;
          body.user_type = "普通用户";
          body.insert_time = dateFormat(new Date(), "yyyy年mm月dd日 hh时SS分ss秒");
          news_user_info.insert(body, (err, result) => {
            if (err) {
              callback(err, null);
            } else {
              if (result) {
                callback(null, { code: 1, msg: '注册成功' });
              } else {
                callback(null, { code: 0, msg: '注册失败' });
              }
            }
          })
        } else {
          callback(null, { code: 0, msg: '用户名或手机号已被注册' });
        }
      }
    ], (err, result) => {
      isError(err, res, db);
      if (result.code === 1) {
        res.redirect(`/login?username=${aesEncrypt(username, keys)}`);
      } else {
        res.render("register", { result, session_username });
      }
      db.close();
    });
  });
});

router.post('/login', function (req, res) {
  var session_username = req.session.username;
  var body = req.body;
  var username = body.username;
  var password = body.password;
  conn((err, db) => {
    isError(err, res, db);
    var news_user_info = db.collection("news_user_info");
    news_user_info.findOne({ status: 1, username: username, password: password }, {}, (err, result) => {
      isError(err, res, db);
      if (result) {
        req.session.username = username;
        req.session.news_user_type = result.user_type;
        res.redirect("/");
      } else {
        res.render("login", { msg: "用户名或密码错误", username: "", session_username });
      }
      db.close();
    });
  });
});

module.exports = router;
